package net.pantolomin.nayo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketOption;
import java.nio.channels.ServerSocketChannel;
import java.util.Map;

import net.pantolomin.nayo.api.ConnectionEventsListener;

/**
 * An acceptor using Java NIO as the backing implementation
 */
@SuppressWarnings("rawtypes")
public class NioServer extends NioConnector<ServerSocketChannel> {
	/**
	 * Create the acceptor
	 * 
	 * @param provider
	 *          the provider
	 * @param hostAddress
	 *          the host's address
	 * @param port
	 *          the port to listen on
	 * @param socketOptions
	 *          the socket options
	 * @param eventsListener
	 *          the listener for incoming data
	 * @throws IOException
	 *           if the communication channel could not be opened
	 */
	NioServer(NioProvider provider, InetAddress hostAddress, int port, Map<SocketOption, Object> socketOptions, ConnectionEventsListener eventsListener)
			throws IOException {
		super(provider, hostAddress, port, socketOptions, eventsListener);
	}

	@Override
	protected ServerSocketChannel initChannel() throws IOException {
		// Create a new non-blocking server socket channel
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		return serverChannel;
	}

	@Override
	protected <T> void setOption(ServerSocketChannel channel, SocketOption<T> option, T value) throws IOException {
		channel.setOption(option, value);
	}

	@Override
	void start() {
		// Start accepting connections
		getProvider().getSelectionLoop().acceptConnections(getChannel(), //
				new InetSocketAddress(getHostAddress(), getPort()));
	}
}